package com.sacc.controller;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.power.common.model.CommonResult;
import com.sacc.pojo.OrderStateAll;
import com.sacc.service.OrderStateAllService;
import com.sacc.util.WXPayUtil;
import com.wechat.pay.contrib.apache.httpclient.WechatPayHttpClientBuilder;
import com.wechat.pay.contrib.apache.httpclient.auth.*;
import com.wechat.pay.contrib.apache.httpclient.cert.CertificatesManager;
import com.wechat.pay.contrib.apache.httpclient.exception.HttpCodeException;
import com.wechat.pay.contrib.apache.httpclient.exception.NotFoundException;
import com.wechat.pay.contrib.apache.httpclient.util.PemUtil;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.junit.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;


import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.security.PrivateKey;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @author 滚~韬
 * @date 2022/4/14 16:39
 */
@RestController
@RequestMapping("/order/ordernumber")
public class OrderNumberController {
    @Autowired
    private OrderStateAllService orderStateAllService;
    @Autowired
    private WXPayUtil wxPayUtil;
    @PostMapping("/create")
    public Map CreateOrderNumber(@RequestBody OrderStateAll stateAll) throws Exception {
        CommonResult result = orderStateAllService.CreateOrderNumber(stateAll);
        return wxPayUtil.CreateOrderNumber((OrderStateAll)result.getData());
    }
    @PostMapping("/callback")
    public Map callback(HttpServletRequest httpServletRequest){
        Map result = new HashMap();
        result.put("code","FAIL");
        try{
            StringBuilder stringBuilder = new StringBuilder();
            //时间戳
            stringBuilder.append(httpServletRequest.getHeaders("Wechatpay-Timestamp")).append("\n");
            //随机串
            stringBuilder.append(httpServletRequest.getHeaders("Wechatpay-Nonce")).append("\n");
            //报文主体
            BufferedReader br = httpServletRequest.getReader();
            String str = null;
            StringBuilder builder = new StringBuilder();
            while((str=br.readLine())!=null){
                builder.append(str);
            }
            stringBuilder.append(builder.toString()).append("\n");

            //验证签名
            if(!WXPayUtil.signVerify(httpServletRequest.getHeader("Wechatpay-Serial"),stringBuilder.toString(),httpServletRequest.getHeader("Wechatpay-Signature"))){
                result.put("message","sign error");
            }
            //解密密文
            ObjectMapper objectMapper = new ObjectMapper();
            String s = WXPayUtil.decryptOrder(builder.toString());
            JsonNode js = objectMapper.readTree(s);
            String out_trade_no = js.get("out_trade_no").textValue();
            String trade_state_desc = js.get("trade_state_desc").textValue();
            if(trade_state_desc.equals("支付成功")){
                orderStateAllService.GoNextState(out_trade_no);
            }
            //验证订单
            result.put("code","SUCCESS");
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (GeneralSecurityException e) {
            throw new RuntimeException(e);
        } catch (NotFoundException e) {
            throw new RuntimeException(e);
        } catch (HttpCodeException e) {
            throw new RuntimeException(e);
        }
        return  result;
    }
    @GetMapping("/query")
    public String queryOrder(@RequestParam String transactionId) throws Exception {
        return WXPayUtil.queryOrder(transactionId);
    }
    //取消订单号
    @GetMapping("/close")
    public String closeOrder(@RequestParam String OrderNumber) throws Exception {
        orderStateAllService.DeleteOrderNumber(OrderNumber);
        return WXPayUtil.closeOrder(OrderNumber);
    }
}
